<?php
//账户业务模块
class AccountService extends TP_Service
{
    public function __construct()
    {
        parent::__construct();
        $this->load->Model("PModel/Account_model");
        $this->load->Model("PModel/Admin_model");
        $this->load->Model("PModel/V_Admin_model");
        $this->load->Model("PModel/V_User_model");
        $this->load->Model("PModel/Menurole_model");
        $this->load->Model("PModel/Actionrole_model");
        $this->load->Model("PModel/AccRole_model");
        $this->load->Model("SModel/Staff_model");
        $this->load->model("SModel/Config_model");

    }

    /**
     * [getAccountInfo description]
     * @Description 通过UUID获取账户主信息，admin用户信息，角色信息
     * @Author      FengPQ
     * @DateTime    2020-07-27T23:03:20+0800
     * @param       [type]                   $uuid [description]
     * @return      [type]                   $is_manage  [是否账户管理]
     */
    public function getAdminInfo($uuid,$is_manage=false)
    {
        //为空判断
        api_params_check($uuid);

        //获取基本用户信息
        $accountInfo = $this->V_Admin_model->get_single(array("uuid" => $uuid));

        //用户不存在
        if (!$accountInfo) {
            throw new \TPException(ErrCode::ErrCode_10403);
        }

        //无效用户情况
        if ($accountInfo['valid'] != EnableState::Enable[TPEnum::Value] && !$is_manage) {
            throw new \TPException(ErrCode::ErrCode_10401);
        }

        return $accountInfo;
    }

    /**
     * [getAccAuth description]
     * @Description 通过UUID获取账户菜单权限
     * @Author      FengPQ
     * @DateTime    2020-07-28T00:07:54+0800
     * @param       [type]                   $uuid [description]
     * @return      [type]                         [description]
     */
    public function getMenuAuth($role_id)
    {
        //为空判断
        api_params_check($role_id);

        $menuAuth = $this->Menurole_model->getMenusByRole($role_id);

        return $menuAuth;
    }

    /**
     * [getActionAuth description]
     * @Description 通过UUID获取账户接口权限
     * @Author      FengPQ
     * @DateTime    2020-08-05T16:47:25+0800
     * @param       [type]                   $uuid [description]
     * @return      [type]                         [description]
     */
    public function getActionAuth($role_id)
    {
        //为空判断
        api_params_check($role_id);

        //获取基本用户信息
        $actionAuth = $this->Actionrole_model->getActionByRole($role_id);

        return $actionAuth;
    }

    /**
     * [ description]
     * @Name        getAccountList
     * @Description 获取用户列表数据
     * @Author      LiAnXu
     * @Date 2020-12-09 13:07:29 星期三
     * @param       [type]                   $type [账户类型]
     * @param       [param]                  $param [搜索条件]
     * @param       [export]                 $export [是否导出]
     * @return      [array]                   [用户列表数据]
     */
    public function getAccountList($type,$param,$export=false){
        if(!$export){
            api_params_check($param['pageNo'],$param['pageSize']);
        }            
        $param=filterNull($param);
        if($type==AccountType::Admin[TPEnum::Value]){            
            $list=$this->V_Admin_model->getList($param,$export);
        }else{
            $list=$this->V_User_model->getList($param,$export);
        }
        return $list;
    }
    /**
     * [ description]
     * @Name        saveAdminInfo
     * @Description 保存后台账户信息
     * @Author      LiAnXu
     * @Date 2020-12-10 12:39:46 星期四
     * @return      [type]                   [description]
     */
    public function saveAdminInfo($data){
        if(!isset($data['usercode']) || !isset($data['username']) || !isset($data['role_id']) || !isset($data['uuid'])){
            exit(retJson(ErrCode::ErrCode_10002));
        }
        if(!is_array($data['role_id'])){
            exit(retJson(ErrCode::ErrCode_10003));
        }
        api_params_check($data['usercode'],$data['username'],$data['role_id'],$data['email']);
        $param=copyArray($data,array('usercode','username','role_id'));
        // 新增
        if(isEmpty($data['uuid'])){
            // 判断账号名是否重复
            $check=$this->Account_model->get_single(array('usercode'=>$data['usercode'],'is_delete'=>DeleteState::UnDelete[TPEnum::Value]));
            if($check){
                exit(retJson(ErrCode::ErrCode_10405));
            }
            $email=$this->Account_model->get_single(array('email'=>$data['email'],'is_delete'=>DeleteState::UnDelete[TPEnum::Value]));
            if($email){
                exit(retJson(ErrCode::ErrCode_10904));
            }
            // 1.新建账户主表
            $salt = md5(GetRandStr(16));

            if(empty($data['password'])){
                $password = getPasswrodWithTwiceEncode(INIT_PWD,$salt);
            }else{
                $password = getPasswrodWithTwiceEncode($data['password'],$salt);
            }
            $uuid=getUuid();
            $param=array(
                'usercode'=>$data['usercode'],
                'username'=>$data['username'],
                'password'=>$password,
                'passsalt'=>$salt,
                'uuid'=>$uuid,
            );
            $id = $this->Account_model->add($param);
            // 2.新建角色表
            foreach ($data['role_id'] as $k => $v) {
                $role=array(
                    'role_id'=>$v,
                    'uuid'=>$uuid
                );
                $this->AccRole_model->add($role);
            }
            return $id;
        }else{
            // 编辑
            $where=array('uuid'=>$data['uuid']);
            // $this->Account_model->updateInfo($param,$where);
            $data=$param;
            if(isset($data['role_id'])){
                unset($data['role_id']);
            }	
            // 1.更新账户信息
            $this->Account_model->update($data,$where);
            // 2.更新角色信息
            // 2.1获取当前账户信息
            $info=$this->Account_model->get_single(array('uuid'=>$where['uuid']));
            if(!$info){
                exit(retJson(ErrCode::ErrCode_10403));
            }
            // 2.2先删除原先的角色信息
            $this->AccRole_model->update(array('is_delete'=>DeleteState::Delete[TPEnum::Value]),array('uuid'=>$info['uuid'],'is_delete'=>DeleteState::UnDelete[TPEnum::Value]));
            // 3.新增新角色
            $this->load->Model("PModel/Role_model");
            foreach ($param['role_id'] as $k => $v) {
                $this->AccRole_model->add(array('role_id'=>$v,'uuid'=>$info['uuid']));
		    }
        }       
        return true;
    }
    
    /**
     * [ description]
     * @Name        changeAccountVaild
     * @Description 方法描述
     * @Author      LiAnXu
     * @Date 2020-12-10 12:58:19 星期四
     * @return      [type]                   [description]
     */
    public function changeAccountVaild($uuid){
        api_params_check($uuid);
		$data=$this->Account_model->get_single(array('uuid'=>$uuid));
		if($data['valid']==EnableState::Enable[TPEnum::Value]){
			$param['valid']=EnableState::Disable[TPEnum::Value];
		}else{			
			$param['valid']=EnableState::Enable[TPEnum::Value];
		}
        $where=array('uuid'=>$data['uuid']);
        $this->Account_model->update($param,$where);
        return true;
    }

    /**
     * [ modifyPwd]
     * @Name        modifyPwd
     * @Description 修改密码
     * @Author      LiAnXu
     * @Date 2021-01-07 13:19:51 星期四
     * @param 密码数组
     * @return  void
     */
    public function modifyPwd($param){
        if(!isset($param['oldPwd']) && !isset($param['newPwd']) && !isset($param['newPwd2'])){
            exit(retJson(ErrCode::ErrCode_10002));
        }
        $detail = $this -> Account_model -> get_single(array("uuid" =>$_SESSION[SESS_HEADER]['uuid']));
        $tPassword = getPasswrodWithTwiceEncode($param["oldPwd"],$detail["passsalt"]);
        if($tPassword != $detail["password"]){
            exit(retJson(ErrCode::ErrCode_10406));
        }
        if($param["newPwd"]!=$param["newPwd2"])
        {
            exit(retJson(ErrCode::ErrCode_10407));
        }
        $salt = md5(GetRandStr(16));
        $password = getPasswrodWithTwiceEncode($param["newPwd"],$salt);
        $update['uuid']=$detail['uuid'];
        $update["password"] = $password;
        $update["passsalt"] = $salt;
        $update["up_pwd_time"] = time();

        $this -> Account_model -> update($update,array('uuid'=>$update['uuid']));


        if($detail['account_type'] == AccountType::Admin[TPEnum::Value]){
            $this->Staff_model -> update(['password' => $param['newPwd']],['aid' => $detail['id']]);
        }
        return true;
    }

    //判断密码是否过期,如果过期就弹窗提示
    public function IfPwdTime(){
        $detail = $this -> Account_model -> get_single(array("uuid" =>$_SESSION[SESS_HEADER]['uuid']));
        $data=$this->Config_model->get_single(array('id'=>4));
        if($data){
            if($detail['up_pwd_time'] != ""){
                $up_pwd_time = date("Y-m-d H:i:s",$detail['up_pwd_time']);//密码的修改时间
                $day = $data['value'];//获取配置的天数
                $expiration_time= date("Y-m-d H:i:s",strtotime("+".$day." day",strtotime($up_pwd_time)));//动态获取过期时间
                // var_dump($up_pwd_time);
                // var_dump($day);
                // var_dump( $expiration_time);
                if(time() >= strtotime($expiration_time)){
                    exit(retJson(ErrCode::ErrCode_11005));
                }else{
                    return true;
                }

            }else{
                exit(retJson(ErrCode::ErrCode_11005)); 
            }
        }else{
            return true;
        }

    }

}
